<template>
  <div class="music-player">
    <div class="audio_top">
      <img src="../images/quotation_marks.svg" alt="">
    </div>
    <!-- <div class="lyrics">
      <transition-group name="fade" tag="div">
        <p
          v-for="(line, index) in parsedLyrics"
          :key="index"
          :class="{ active: index === currentLineIndex }"
        >
          {{ line.txt }}
        </p>
      </transition-group>
    </div> -->
    <div class="current_img">
      <img :src="currentSong.img" alt="">
    </div>

    <div class="controls">
      <button @click="toggleMute" class="control-button-Muted">
        <img v-show="isMuted" src="../images/mute.png" alt="">
        <img v-show="!isMuted" src="../images/unmute.png" alt="">
      </button>
      <div class="center-controls">
        <button disabled @click="playPrevious" class="control-button">
          <img class="prev_btn" src="../images/prev_btn.png" alt="">
        </button>
        <button 
          @click="togglePlay" 
          class="play-button">
            <img v-show="isPlaying" src="../images/stop.png" alt="">
            <img v-show="!isPlaying" style="margin-left: .5rem;" src="../images/play.png" alt="">
        </button>
        <button disabled @click="playNext" class="control-button">
          <img class="next_btn" src="../images/prev_btn.png" alt="">
        </button>
      </div>
      
    </div>
   

    <div class="progress-bar">
      <vue-slider
        v-model="currentTime"
        :max="100"
        :min="0"
        :tooltip="'none'"
        @drag-end="onSliderChange"
        :width="'100%'"
        :height="5"
        class="progress-slider"
      />
      <div class="time-display">
        {{ formatTime((currentTime / 100) * duration) }} / {{ formatTime(duration) }}
      </div>
      <div class="current-song">
        <p>{{ currentSong.title }}</p> <!-- 显示当前歌曲名称 -->
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, onBeforeUnmount, watch } from 'vue';
import Lyric from 'lyric-parser';
import VueSlider from 'vue-slider-component';
import 'vue-slider-component/theme/default.css';
import { useUserStore } from '../store/user';
const {userState} = useUserStore()
let songs = reactive([])
const props = defineProps({
  musicData: {
    type: Object,
    required: true
  }
});

console.log("props:", props)
songs.push(props.musicData)


const audio = new Audio(songs[0].src);
const isPlaying = ref(false);
const currentTime = ref(0); 
const duration = ref(0);
const currentLineIndex = ref(0);
const parsedLyrics = ref([]);
const lyricParser = ref(null);
const currentSongIndex = ref(0); 
const currentSong = ref(songs[currentSongIndex.value]);
const isMuted = ref(false);
let isLyricPaused = false;



watch(()=>userState.currentAudioIndex, (val) => {
  console.log(userState.currentAudioIndex)
  isPlaying.value = false
  audio.pause()
})



// 切换静音状态
const toggleMute = () => {
  isMuted.value = !isMuted.value;
  audio.muted = isMuted.value; // 设置音频的静音状态
  console.log(`静音状态: ${isMuted.value ? "静音" : "取消静音"}`);
};

// 初始化歌词
const initializeLyric = async () => {
  try {
    const response = await fetch(currentSong.value.lrc);
    if (!response.ok) {
      throw new Error(`Failed to load lyrics: ${response.statusText}`);
    }
    const lyricsText = await response.text();
    const formattedLyrics = lyricsText.replace(/(\[\d{2}:\d{2}\.\d{3}\])/g, '\n$1').trim();

    // 清除上次的歌词状态
    if (lyricParser.value) {
      lyricParser.value.stop();
    }

    lyricParser.value = new Lyric(formattedLyrics, ({ lineNum, txt }) => {
      if (!isLyricPaused) {
        currentLineIndex.value = lineNum;
        console.log(`歌词切换: 行号=${lineNum}, 文本="${txt}", currentLineIndex=${currentLineIndex.value}`);
        scrollToCurrentLyric();
      }
    });

    parsedLyrics.value = lyricParser.value.lines;
  } catch (error) {
    console.error("Error initializing lyrics:", error);
  }
};

// 格式化时间
const formatTime = (time) => {
  const minutes = Math.floor(time / 60);
  const seconds = Math.floor(time % 60).toString().padStart(2, '0');
  return `${minutes}:${seconds}`;
};

// 滚动到当前歌词
const scrollToCurrentLyric = () => {
  const activeLine = document.querySelector('.lyrics .active');
  const lyricsContainer = document.querySelector('.lyrics');
  if (activeLine && lyricsContainer) {
    const linePosition = activeLine.offsetTop;
    const lineHeight = activeLine.clientHeight;
    const containerHeight = lyricsContainer.clientHeight;

    // 增加一点偏移量以调整居中位置
    const scrollPosition = linePosition - containerHeight / 2 + lineHeight / 2  - containerHeight/2; // 调整偏移量

    // const scrollPosition = containerHeight / 2 ; // 调整偏移量

    console.log('linePosition:', linePosition)
    console.log('lineHeight:', lineHeight)
    console.log('containerHeight:', containerHeight)
    console.log('scrollPosition:', scrollPosition)

    lyricsContainer.scrollTo({
      top: scrollPosition,
      behavior: 'smooth',
    });
  }
};


// 切换播放/暂停
const togglePlay = () => {
  isPlaying.value = !isPlaying.value;
  console.log(`当前播放状态: ${isPlaying.value ? "播放" : "暂停"}`);
  
  if (isPlaying.value) {
    audio.play().catch(error => {
      console.error("Playback failed:", error);
    });
    isLyricPaused = false;
    lyricParser.value.play(currentTime.value * duration.value * 10);
  } else {
    audio.pause();
    isLyricPaused = true;
    if (lyricParser.value) {
      lyricParser.value.stop(); // 停止歌词解析器
    }
  }
};

// 播放上一曲
const playPrevious = () => {
  currentSongIndex.value = (currentSongIndex.value - 1 + songs.length) % songs.length;
  loadSong();
};

// 播放下一曲
const playNext = () => {
  currentSongIndex.value = (currentSongIndex.value + 1) % songs.length;
  loadSong();
};

// 加载歌曲
const loadSong = () => {
  if (lyricParser.value) {
    lyricParser.value.stop();
  }

  currentSong.value = songs[currentSongIndex.value];
  audio.src = currentSong.value.src;
  audio.load();
  
  currentTime.value = 0;
  initializeLyric(); // 重新初始化歌词
  if (isPlaying.value) {
    audio.play().catch(error => {
      console.error("Playback failed:", error);
    });
  }
};

// 更新滑块变化时的音频和歌词
const onSliderChange = () => {
  const newCurrentTime = (currentTime.value / 100) * duration.value;
  audio.currentTime = newCurrentTime;
  lyricParser.value.stop();
  lyricParser.value.seek(newCurrentTime * 1000);
};

// 监听播放进度并同步歌词
const updateDuration = () => {
  duration.value = audio.duration;
};

const updateCurrentTime = () => {
  currentTime.value = (audio.currentTime / duration.value) * 100;
  lyricParser.value.seek(audio.currentTime * 1000);
};

const handleEnded = () => {
  isPlaying.value = false;
  currentTime.value = 0;
  playNext();
};

onMounted(() => {
  initializeLyric().catch(error => {
    console.error("Error during initialization:", error);
  });

  audio.addEventListener('loadedmetadata', updateDuration);
  audio.addEventListener('timeupdate', updateCurrentTime);
  audio.addEventListener('ended', handleEnded);
});

// 清理事件监听器
onBeforeUnmount(() => {
  audio.removeEventListener('loadedmetadata', updateDuration);
  audio.removeEventListener('timeupdate', updateCurrentTime);
  audio.removeEventListener('ended', handleEnded);
});
</script>


<style scoped>
.audio_top {
  width: 100%;
}

.audio_top img {
  width: 4.8rem;
}

.music-player {
  width: 38.0rem;
  height: 57.0rem;
  padding: 3.0rem;
  box-sizing: border-box;
  background: linear-gradient(180deg, rgba(46, 46, 63, 1) 0%, rgba(137, 144, 136, 1) 100%);
  border-radius: 1.0rem;
  box-shadow: 0 .4rem 2.0rem rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  font-family: Arial, sans-serif;
}

.current-song {
  width: 100%;
  text-align: left;
  font-size: 1.8rem;
  color: #FFF;
  margin-top: 2.0rem;
}

.controls {
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center; /* 垂直居中 */
}

.control-button-Muted {
  background: none;
  border: 0;
  cursor: pointer;
  margin-right: auto; /* 将 Muted 按钮推到左侧 */
}

.control-button-Muted img{
  width: 1.6rem;
  height: 1.6rem;
}


.center-controls {
  display: flex; /* 使用 Flexbox 进行布局 */
  justify-content: center; /* 居中对齐其他按钮 */
  align-items: center;
  gap: 1.5rem; 
  flex-grow: 1; /* 允许 center-controls 填充剩余空间 */
}

.control-button {
  width: 2.6rem;
  height: 2.60rem;
  background: rgba(255, 255, 255, 0.1);
  border: none;
  border-radius: .5rem;
  cursor: pointer;
  transition: background-color 0.3s;
  padding: .5rem;
  border-radius: 10.0rem;
}

.control-button img {
  width: 1.6rem;
  height: 1.6rem;
}

.control-button:hover {
  background: rgba(255, 255, 255, 0.5);
}

.play-button {
  padding: 1.0rem 2.0rem;
  border: none;
  border-radius: 100%;
  width: 6.0rem;
  height: 6.0rem;
  background: linear-gradient(85deg, rgba(218, 33, 74, .8) 15%, rgba(137, 54, 240, .8) 88%);
  color: white;
  font-weight: bold;
  cursor: pointer;
  transition: background-color 0.5s;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}

.play-button:hover {
  background: linear-gradient(85deg, rgba(218, 33, 74, 1) 15%, rgba(137, 54, 240, 1) 88%);
}

.play-button img {
  width: 2.0rem;
  height: 2.0rem;
}

.progress-bar {
  display: flex;
  align-items: center;
  flex-direction: column;
  width: 100%;
}

.progress-slider {
  width: 100%;
}

.time-display {
  width: 100%;
  text-align: right;
  margin-top: .5rem;
  font-size: 1.2rem;
  color: #CCC;
}

/* 添加动画效果 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s ease;
}
.fade-enter, .fade-leave-to /* .fade-leave-active in <2.1.8 */ {
  opacity: 0;
}

.next_btn {
  transform: rotate(180deg);
}

.lyrics {
  max-height: 26.0rem; /* 调整为合适的高度 */
  overflow-y: auto;
  padding: 1.0rem;
  border-radius: .5rem;
}

.lyrics p {
  margin: .5rem 0;
  font-size: 1.8rem;
  line-height: 2.7rem;
  transition: color 0.3s, transform 0.5s ease;
}

.lyrics .active {
  color: #3498db;
  font-weight: bold;
  /* transform: scale(1.1); */
}


.current_img {
  width: 100%;
  height: 27rem;
}

.current_img img {
  width: 100%;
  height: 100%;
}

</style>
